import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {AxdrEnum} from "../asn1.axdr/AxdrEnum";
import {Unsigned16} from "./Unsigned16";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";


export class TI implements AxdrType {


    dataCode: Buffer | null = null;
    unit: AxdrEnum | null = null;
    inter: Unsigned16 | null = null;

    constructor() {
    }

    set_dataCode(dataCode: Buffer) {
        this.dataCode = dataCode;
    }

    set_unit_inter(unit: AxdrEnum, inter: Unsigned16) {
        this.unit = unit;
        this.inter = inter;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;
        this.unit = new AxdrEnum();
        this.unit.set_const();
        codeLength += this.unit.decode(input);

        this.inter = new Unsigned16();
        this.inter.set_const();
        codeLength += this.inter.decode(input);
        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.unit != null && this.inter != null) {
                codeLength = 0;
                codeLength += this.inter.encode(output);
                codeLength += this.unit.encode(output);
            } else {
                throw new Error("encode error，unit or inter is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess)
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.unit != null && this.inter != null) {
            return "sequence: {" + "unit: " + this.unit + ", inter: " + this.inter + "}";
        } else {
            return "unit or inter is null";
        }
    }

}
